<?php
if (!function_exists('captcha_for_api')) {
    /**
     * @param string $config
     * @return array
     */
    function captcha_for_api(string $config = 'default'): array
    {
        return app('captcha')->create($config, true);
    }
}

if (!function_exists('success')) {
    /**
     * @param string $config
     * @return \Illuminate\Http\JsonResponse
     */
    function success(array $data = [], string $msg = 'success'): \Illuminate\Http\JsonResponse
    {
        $result = [
            'code' => 200,
            'msg' => $msg,
        ];
        $result = array_merge($result, $data);
        return response()->json($result, 200, [], JSON_UNESCAPED_UNICODE);
    }
}

if (!function_exists('error')) {
    /**
     * @param string $config
     * @return \Illuminate\Http\JsonResponse
     */
    function error(string $msg = 'fail', int $code = 500): \Illuminate\Http\JsonResponse
    {
        $result = [
            'code' => $code,
            'msg' => $msg,
        ];
        return response()->json($result, 200, [], JSON_UNESCAPED_UNICODE);
    }
}

if (!function_exists('page_format')) {
    /**
     *
     */
    function page_format($paginator)
    {
        $result = [
            'rows' => $paginator->items(),
            'total' => $paginator->total(), // 获取结果集中的数据总数
            'last_page' => $paginator->lastPage(),
            'currentPage' => $paginator->currentPage()
        ];
        return $result;
    }
}

if (!function_exists('makeTree')) {
    /**
     *
     */
    function makeTree($datas, $idKey = 'id', $pidKey = 'parent_id')
    {
        $refer = array();
        $tree = array();
        foreach ($datas as $k => $v) {
            $refer[$v[$idKey]] = &$datas[$k]; //创建主键的数组引用
        }

        foreach ($datas as $k => $v) {
            $pid = $v[$pidKey];  //获取当前分类的父级id
            if (!$pid) {
                $tree[] = &$datas[$k];  //顶级栏目
            } else {
                if (isset($refer[$pid])) {
                    $refer[$pid]['children'][] = &$datas[$k]; //如果存在父级栏目，则添加进父级栏目的子栏目数组中
                }
            }
        }
        return count($tree) > 0 ? $tree : $datas;
    }
}

if (!function_exists('get_last_node')) {
    /**
     *
     */
    function get_last_node($tree, &$result)
    {
        foreach ($tree as $item) {
            if (isset($item['children'])) {
                get_last_node($item['children'], $result);
            } else {
                $result[] = $item['id'];
            }
        }
        return true;
    }
}

function generateRouters($trees)
{
    //0 目录 1菜单 2按钮接口
    $new_data = [];
    foreach ($trees as $data) {
        $temp_data = [
            'name' => $data['component'] ? str_replace('/', '', $data['component']) : ucfirst($data['path']),
        ];
        $temp_data['path'] = $data['path'];
        //目录
        if ($data['menu_type'] == 'M' && $data['parent_id'] == 0) {
            //目录
            $temp_data['path'] = "/{$data['path']}";
        }
        //菜单
        if ($data['menu_type'] == 'C' && $data['parent_id'] == 0) {
            $temp_data['path'] = "/";
        }

        $temp_data['hidden'] = $data['visible'] == 0 ? true : false;

        if ($data['menu_type'] == 'M' && isset($data['children']) && count($data['children']) > 0 && $data['parent_id'] > 0) {
            $temp_data['component'] = $data['component'] ? $data['component'] : 'ParentView';
        } else {
            $temp_data['component'] = $data['component'] ? $data['component'] : 'Layout';
        }

        if (isset($data['children']) && count($data['children']) > 0 && $data['menu_type'] === 'M') {
            $temp_data['redirect'] = "noRedirect";
            $temp_data['alwaysShow'] = true;
            $temp_data['children'] = generateRouters($data['children']);
        }
        $temp_data['meta'] = [
            'title'  => $data['menu_name'],
            'icon'  => $data['icon'],
            'noCache'  => $data['is_cache'] ? false : true,
        ];
        $new_data[] = $temp_data;
    }
    return $new_data;
}

/**
 * @param $arr
 * @param $key_name
 * @return array
 * 将数据库中查出的列表以指定的 id 作为数组的键名
 */
function convert_arr_key($arr, $key_name)
{
    $arr2 = array();
    foreach ($arr as $key => $val) {
        $arr2[$val[$key_name]] = $val;
    }
    return $arr2;
}

function get_api_secret($salt)
{
    return md5($salt . env('API_USER_KEY') . md5($salt));
}

function api_sign($params, $api_key)
{
    unset($params['sign']);
    ksort($params);
    $params['apikey'] = $api_key;
    $str = http_build_query($params);
    $str = urldecode($str);
    $sign = md5($str);
    return strtoupper($sign);
}

function sock_post($url, $param)
{
    $host = parse_url($url, PHP_URL_HOST);
    $port = parse_url($url, PHP_URL_PORT) ? intval(parse_url($url, PHP_URL_PORT)) : 80;
    $errno = '';
    $errstr = '';
    $timeout = 30;

    $data = http_build_query($param);

    // create connect
    $fp = fsockopen($host, $port, $errno, $errstr, $timeout);

    if (!$fp) {
        return false;
    }

    // send request
    $out = "POST {$url} HTTP/1.1\r\n";
    $out .= "Host:{$host}\r\n";
    $out .= "Content-type:application/x-www-form-urlencoded\r\n";
    $out .= "Content-length:" . strlen($data) . "\r\n";
    $out .= "Connection:close\r\n\r\n";
    $out .= "{$data}";

    fwrite($fp, $out);

    //忽略执行结果；否则等待返回结果
    if (false) {
        $ret = '';
        while (!feof($fp)) {
            $ret .= fgets($fp, 128);
        }
    }
    //20毫秒
    usleep(20000); //fwrite之后马上执行fclose，nginx会直接返回499
    fclose($fp);
}
function sock_get($url, $param)
{
    $host = parse_url($url, PHP_URL_HOST);
    $port = parse_url($url, PHP_URL_PORT) ? intval(parse_url($url, PHP_URL_PORT)) : 80;
    //    $port =  80;
    $errno = '';
    $errstr = '';
    $timeout = 30;

    $url = $url . '?' . http_build_query($param);
    file_put_contents("../api_resource/logs/" . date("Ymd") . "_queuedata.log",  "url----" . print_r($url, 1) . PHP_EOL, FILE_APPEND);
    // create connect
    $fp = fsockopen($host, $port, $errno, $errstr, $timeout);

    if (!$fp) {
        return false;
    }

    // send request
    $out = "GET {$url} HTTP/1.1\r\n";
    $out .= "Host:{$host}\r\n";
    $out .= "Connection:close\r\n\r\n";
    //    file_put_contents("22.txt",$out."*******\n",FILE_APPEND);
    fwrite($fp, $out);

    //忽略执行结果；否则等待返回结果
    if (false) {
        $ret = '';
        while (!feof($fp)) {
            $ret .= fgets($fp, 128);
        }
    }
    usleep(20000); //fwrite之后马上执行fclose，nginx会直接返回499
    fclose($fp);
}
function sock_queue($order_id, $type, $params = [])
{
    $data = array_merge([
        'act' => $type,
        'order_id' => $order_id
    ], $params);

    sock_get(env('QUEUE_URL'), $data);
}
